package com.guxingke.gsb.server;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.server.handler.gzip.GzipHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * Created by 孤星可 on 2015/11/22.
 *
 * @author guxingke
 * @since 2015/11/22
 */
public class FileServer {
    private Server server;
    private int port;

    public FileServer(int port) {
        this.port = port;
    }

    public void startPreview(String resourcePath) {
        server = new Server(port);
        ResourceHandler resourceHandler = new ResourceHandler();
        resourceHandler.setDirectoriesListed(true);
        resourceHandler.setWelcomeFiles(new String[]{"index.html"});
        resourceHandler.setResourceBase(resourcePath);

        GzipHandler gzip = new GzipHandler();
        server.setHandler(gzip);
        HandlerList handlers = new HandlerList();
        handlers.setHandlers(new Handler[]{resourceHandler, new ShutDownServerHandler("stop"), new DefaultHandler()});
        gzip.setHandler(handlers);

        try {
            server.start();
            String url = "http://localhost:" + port;
            openBrowser(url);
            server.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void openBrowser(String url) {
        if (Desktop.isDesktopSupported()) {
            Desktop desktop = Desktop.getDesktop();
            try {
                desktop.browse(new URI(url));
            } catch (IOException | URISyntaxException e) {
                e.printStackTrace();
            }
        } else {
            Runtime runtime = Runtime.getRuntime();
            try {
                runtime.exec("xdg-open " + url);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void shutdown() {
        try {
            // server.stop(),gracefully to close jetty ,but too slowly
            // server.stop();
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class ShutDownServerHandler extends HandlerWrapper {
        private String token;

        ShutDownServerHandler(String token) {
            this.token = token;
        }

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            if (!target.startsWith("/shutdown")) {
                super.handle(target, baseRequest, request, response);
                return;
            }
            String token = baseRequest.getParameter("token");
            if (this.token.endsWith(token)) {
                shutdown();
            }
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
    }
}
